// 设置变量
var word = document.getElementById('word');             //搜索框
var sousuo = document.getElementById('sousuo');         //搜索图形
var list = document.querySelector('.list');             //搜索列表
var pic = document.getElementById('musicpic');          //图片
var lyric = document.getElementById('lyric');           ///歌词
var jdt = document.getElementById('jdt');               //进度条
var musicname = document.getElementById('name');        //歌名-歌手
var state_go = document.getElementById('go');           //播放键
var state_stop = document.getElementById('stop');       //暂停键
var timebox = document.getElementsByClassName('timebox');
var songtime = document.getElementById('songtime');
var songnowtime = document.getElementById('songnowtime');
var yinliang = document.getElementById('slice');
var tip = document.getElementById('tip');
var viptip = document.getElementById('viptip');
var audio = new Audio();
var nowtime;
var timer;
var musictime;
var toltimestr;
var choose;
var timeArr = [];
var lrcArr = [];
const URL = "http://1.15.232.61:3000";
//远程 1.15.232.61


//回车搜索
function huiche(e) {
    if (e.key === 'Enter') {
        search();
    }
}
document.addEventListener('keydown',huiche);


//点击s键
document.addEventListener('keyup', function (e) {
    if (e.key == 's') {
        word.focus();
    }
})

//点击搜索
sousuo.inclick = search;

// 搜索歌曲
async function search() {
    let content = word.value;
    //包含歌曲信息的数组res
    const response = await fetch(`${URL}/cloudsearch?keywords=${content}`);
    console.log('response',response);
    const res = await response.json();
    console.log(res);
    const data = res.result.songs;
    console.log('data',data);
    ///将arr的数据赋值给lis
    let str = '';
    data.forEach(val => {
        str += `<li class="item">${val.name}</li>`
    });
    list.innerHTML = str;
    const items = document.querySelectorAll('.list .item');
    const lrcitems = document.querySelectorAll('.list .id');
    list.style.display = 'block'    // 展示搜索列表

    list.addEventListener('mouseover', function () {
        this.style.cursor = 'default';
    })

    for (let i = 0; i < items.length; i++) {

        items[i].onclick = async function () {   //点击一首之后
            resetAudio();
            word.value = '';
            list.style.display = 'none';        //列表隐藏
            showZanting();                      //播放  => 暂停
            choose = true;                      //标记播放/暂停

            //歌曲详情 
            const q = await fetch(`${URL}/song/detail?ids=` + data[i].id)
            const xiangqing = await q.json();

            //专辑封面,歌手+歌名,歌曲时长
            pic.src = xiangqing.songs[0].al.picUrl;
            musicname.innerText = xiangqing.songs[0].name + `-` + xiangqing.songs[0].ar[0].name;
            musictime = xiangqing.songs[0].dt;
            
            //音频
            audio.pause()
            const a = await fetch(`${URL}/song/url?id=` + data[i].id);
            const b = await a.json();
            audio.src = b.data[0].url;
            
            //歌词
            const l = await fetch(`${URL}/lyric?id=` + data[i].id)
            const r = await l.json();
            let lrc = r.lrc.lyric;

            //修改进度条range最大值 
            jdt.max = musictime / 1000;
            
            //播放歌曲
            audio.play();
            
            //时长显示
            songtime.innerHTML = '/' + changetimestyle(jdt.max);
            
            //歌词同步
            createLRC(lrc);

            //进度条滑动
            timer = setInterval(jdtChange, 1000);

            ///点击暂停键
            state_stop.addEventListener('click', () => { zantingonclick() });

            ///点击播放键
            state_go.addEventListener('click', () => { bofangonclick() });

            ///会员歌曲
            vipMusic(xiangqing.songs[0].fee);
        }
    }
}

//重置
function resetAudio() {
    jdt.value = 0;          //进度条回到开头
    clearInterval(timer);   //进度条停止计时
    showBofang();
    lyric.innerHTML = '';   //清空歌词列表
    lrcArr = [];            //清空歌词数组
    timeArr = [];           // 清空歌词时间
}

//音量
yinliang.onchange = function () {
    audio.volume = (yinliang.value / 100).toFixed(2);
    if (yinliang.value == 0) {
        tip.style.display = 'block';
        const tiptime = setTimeout(() => {
            tip.style.display = 'none';
        }, 1500);
    }
}

//会员歌曲
function vipMusic(fee) {
    if (fee == 1) {
        viptip.style.display = 'block';
        const viptiptime = setTimeout(() => {
            viptip.style.display = 'none';
        }, 1500);
        musictime = 30 * 1000;
    }
}

//状态按钮改变:显示暂停键
function showZanting() {
    state_go.style.display = 'none';
    state_stop.style.display = 'block';
}

//状态按钮改变:显示播放键
function showBofang() {
    state_go.style.display = 'block';
    state_stop.style.display = 'none';
}

//点击播放键
function bofangonclick() {
    choose = true;
    audio.play();
    showZanting();
    timer = setInterval(jdtChange, 1000);
}

// 点击暂停键
function zantingonclick() {
    choose = false;
    clearInterval(timer);
    audio.pause();
    showBofang();
}

// 修改总时间格式
function changetimestyle(t) {
    let min = parseInt(t / 60);
    let sec = parseInt(t % 60);
    return changenumstyle(min) + ':' + changenumstyle(sec);
}

// 修改数字显示格式
function changenumstyle(num) {
    if (num < 10) {
        return '0' + num;
    }
    else return num;
}

// 进度条滑动                    
function jdtChange() {
    let value = parseFloat($("#jdt").val());//数值型
    if (value == jdt.max || choose == false) {
        return;
    } else {
        $("#jdt").val(++value);
    }
}

// 拖动进度条
jdt.onchange = function (nowmin, nowsec) {
    choose = false;
    clearInterval(timer);
    audio.currentTime = jdt.value
    if (state_go.style.display === 'none') {
        choose = true;
        timer = setInterval(jdtChange, 1000);
    }
}

// 处理歌词
function createLRC(lrc) {
    const reg = /\[(\d{2}:\d{2}).\d{2,}\]((.+)|(.?))/;  //正则
    let lrcs = lrc.split('\n');
    if (lrcs.length > 10) {
        for (var j = 0; j < lrcs.length - 1; j++) {
            let tc = reg.exec(lrcs[j]);
            timeArr.push(tc[1]);            //把时间放到时间数组
            lrcArr.push(tc[2]);             //把歌词放到歌词数组
        }
        let str = '';

        //遍历歌词数组，放到ul标签
        lrcArr.forEach((item, index) => {
            str += `<li class = "${index == 0 ? `active` : ''}">${item}</li>`;
        })
        lyric.innerHTML = str;
    }
    else {
        lyric.innerHTML = '此歌曲为纯音乐，请欣赏~';
    }
}

// 音频同步
audio.addEventListener('timeupdate', function () {
    const { currentTime } = this;
    const timestr = changetimestyle(currentTime);
    toltimestr = changetimestyle(musictime / 1000);
    songnowtime.innerText = timestr;
    
    //判断timeArr中与当前时间timearr匹配的索引，不为-1时滚动
    let index = timeArr.findIndex(item => item == timestr)
    console.log('lyric.top\n' + lyric.style.top);
    //歌词滚动
    if (index != -1 && lyric.children.length) {
        lyric.style.top = 129 - index * 20 + 'px';
        //其他索引列类名为空
        [...lyric.children].forEach(item => item.className = '')
        //当前索引列加类名
        lyric.children[index].className = 'active';
    }
    if (timestr == toltimestr) {
        resetAudio();
    }
})